* Upgrade old skin preferences properly at Special:Preferences
[lhc/web/wiklou.git] / includes / User.php
1 <?php
2 /**
3 * See user.txt
4 *
5 * @package MediaWiki
6 */
7
8 /**
9 *
10 */
11 require_once( 'WatchedItem.php' );
12
13 # Number of characters in user_token field
14 define( 'USER_TOKEN_LENGTH', 32 );
15
16 # Serialized record version
17 define( 'MW_USER_VERSION', 2 );
18
19 /**
20 *
21 * @package MediaWiki
22 */
23 class User {
24 /**#@+
25 * @access private
26 */
27 var $mId, $mName, $mPassword, $mEmail, $mNewtalk;
28 var $mEmailAuthenticated;
29 var $mRights, $mOptions;
30 var $mDataLoaded, $mNewpassword;
31 var $mSkin;
32 var $mBlockedby, $mBlockreason;
33 var $mTouched;
34 var $mToken;
35 var $mRealName;
36 var $mHash;
37 var $mGroups;
38 var $mVersion; // serialized version
39
40 /** Construct using User:loadDefaults() */
41 function User() {
42 $this->loadDefaults();
43 $this->mVersion = MW_USER_VERSION;
44 }
45
46 /**
47 * Static factory method
48 * @param string $name Username, validated by Title:newFromText()
49 * @return User
50 * @static
51 */
52 function newFromName( $name ) {
53 # Force usernames to capital
54 global $wgContLang;
55 $name = $wgContLang->ucfirst( $name );
56
57 # Clean up name according to title rules
58 $t = Title::newFromText( $name );
59 if( is_null( $t ) ) {
60 return null;
61 }
62
63 # Reject various classes of invalid names
64 $canonicalName = $t->getText();
65 global $wgAuth;
66 $canonicalName = $wgAuth->getCanonicalName( $t->getText() );
67
68 if( !User::isValidUserName( $canonicalName ) ) {
69 return null;
70 }
71
72 $u = new User();
73 $u->setName( $canonicalName );
74 $u->setId( $u->idFromName( $canonicalName ) );
75 return $u;
76 }
77
78 /**
79 * Factory method to fetch whichever use has a given email confirmation code.
80 * This code is generated when an account is created or its e-mail address
81 * has changed.
82 *
83 * If the code is invalid or has expired, returns NULL.
84 *
85 * @param string $code
86 * @return User
87 * @static
88 */
89 function newFromConfirmationCode( $code ) {
90 $dbr =& wfGetDB( DB_SLAVE );
91 $name = $dbr->selectField( 'user', 'user_name', array(
92 'user_email_token' => md5( $code ),
93 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
94 ) );
95 if( is_string( $name ) ) {
96 return User::newFromName( $name );
97 } else {
98 return null;
99 }
100 }
101
102 /**
103 * Serialze sleep function, for better cache efficiency and avoidance of
104 * silly "incomplete type" errors when skins are cached
105 */
106 function __sleep() {
107 return array( 'mId', 'mName', 'mPassword', 'mEmail', 'mNewtalk',
108 'mEmailAuthenticated', 'mRights', 'mOptions', 'mDataLoaded',
109 'mNewpassword', 'mBlockedby', 'mBlockreason', 'mTouched',
110 'mToken', 'mRealName', 'mHash', 'mGroups' );
111 }
112
113 /**
114 * Get username given an id.
115 * @param integer $id Database user id
116 * @return string Nickname of a user
117 * @static
118 */
119 function whoIs( $id ) {
120 $dbr =& wfGetDB( DB_SLAVE );
121 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
122 }
123
124 /**
125 * Get real username given an id.
126 * @param integer $id Database user id
127 * @return string Realname of a user
128 * @static
129 */
130 function whoIsReal( $id ) {
131 $dbr =& wfGetDB( DB_SLAVE );
132 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), 'User::whoIsReal' );
133 }
134
135 /**
136 * Get database id given a user name
137 * @param string $name Nickname of a user
138 * @return integer|null Database user id (null: if non existent
139 * @static
140 */
141 function idFromName( $name ) {
142 $fname = "User::idFromName";
143
144 $nt = Title::newFromText( $name );
145 if( is_null( $nt ) ) {
146 # Illegal name
147 return null;
148 }
149 $dbr =& wfGetDB( DB_SLAVE );
150 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), $fname );
151
152 if ( $s === false ) {
153 return 0;
154 } else {
155 return $s->user_id;
156 }
157 }
158
159 /**
160 * does the string match an anonymous IPv4 address?
161 *
162 * Note: We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
163 * address because the usemod software would "cloak" anonymous IP
164 * addresses like this, if we allowed accounts like this to be created
165 * new users could get the old edits of these anonymous users.
166 *
167 * @bug 3631
168 *
169 * @static
170 * @param string $name Nickname of a user
171 * @return bool
172 */
173 function isIP( $name ) {
174 return preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/",$name);
175 /*return preg_match("/^
176 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
177 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
178 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
179 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
180 $/x", $name);*/
181 }
182
183 /**
184 * Is the input a valid username?
185 *
186 * Checks if the input is a valid username, we don't want an empty string,
187 * an IP address, anything that containins slashes (would mess up subpages),
188 * is longer than the maximum allowed username size or doesn't begin with
189 * a capital letter.
190 *
191 * @param string $name
192 * @return bool
193 * @static
194 */
195 function isValidUserName( $name ) {
196 global $wgContLang, $wgMaxNameChars;
197
198 if ( $name == ''
199 || User::isIP( $name )
200 || strpos( $name, '/' ) !== false
201 || strlen( $name ) > $wgMaxNameChars
202 || $name != $wgContLang->ucfirst( $name ) )
203 return false;
204
205 // Ensure that the name can't be misresolved as a different title,
206 // such as with extra namespace keys at the start.
207 $parsed = Title::newFromText( $name );
208 if( is_null( $parsed )
209 || $parsed->getNamespace()
210 || strcmp( $name, $parsed->getPrefixedText() ) )
211 return false;
212 else
213 return true;
214 }
215
216 /**
217 * Is the input a valid password?
218 *
219 * @param string $password
220 * @return bool
221 * @static
222 */
223 function isValidPassword( $password ) {
224 global $wgMinimalPasswordLength;
225 return strlen( $password ) >= $wgMinimalPasswordLength;
226 }
227
228 /**
229 * Does the string match roughly an email address ?
230 *
231 * There used to be a regular expression here, it got removed because it
232 * rejected valid addresses. Actually just check if there is '@' somewhere
233 * in the given address.
234 *
235 * @todo Check for RFC 2822 compilance
236 * @bug 959
237 *
238 * @param string $addr email address
239 * @static
240 * @return bool
241 */
242 function isValidEmailAddr ( $addr ) {
243 return ( trim( $addr ) != '' ) &&
244 (false !== strpos( $addr, '@' ) );
245 }
246
247 /**
248 * Count the number of edits of a user
249 *
250 * @param int $uid The user ID to check
251 * @return int
252 */
253 function edits( $uid ) {
254 $fname = 'User::edits';
255
256 $dbr =& wfGetDB( DB_SLAVE );
257 return $dbr->selectField(
258 'revision', 'count(*)',
259 array( 'rev_user' => $uid ),
260 $fname
261 );
262 }
263
264 /**
265 * probably return a random password
266 * @return string probably a random password
267 * @static
268 * @todo Check what is doing really [AV]
269 */
270 function randomPassword() {
271 global $wgMinimalPasswordLength;
272 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
273 $l = strlen( $pwchars ) - 1;
274
275 $pwlength = max( 7, $wgMinimalPasswordLength );
276 $digit = mt_rand(0, $pwlength - 1);
277 $np = '';
278 for ( $i = 0; $i < $pwlength; $i++ ) {
279 $np .= $i == $digit ? chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
280 }
281 return $np;
282 }
283
284 /**
285 * Set properties to default
286 * Used at construction. It will load per language default settings only
287 * if we have an available language object.
288 */
289 function loadDefaults() {
290 static $n=0;
291 $n++;
292 $fname = 'User::loadDefaults' . $n;
293 wfProfileIn( $fname );
294
295 global $wgContLang, $wgDBname;
296 global $wgNamespacesToBeSearchedDefault;
297
298 $this->mId = 0;
299 $this->mNewtalk = -1;
300 $this->mName = false;
301 $this->mRealName = $this->mEmail = '';
302 $this->mEmailAuthenticated = null;
303 $this->mPassword = $this->mNewpassword = '';
304 $this->mRights = array();
305 $this->mGroups = array();
306 $this->mOptions = User::getDefaultOptions();
307
308 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
309 $this->mOptions['searchNs'.$nsnum] = $val;
310 }
311 unset( $this->mSkin );
312 $this->mDataLoaded = false;
313 $this->mBlockedby = -1; # Unset
314 $this->setToken(); # Random
315 $this->mHash = false;
316
317 if ( isset( $_COOKIE[$wgDBname.'LoggedOut'] ) ) {
318 $this->mTouched = wfTimestamp( TS_MW, $_COOKIE[$wgDBname.'LoggedOut'] );
319 }
320 else {
321 $this->mTouched = '0'; # Allow any pages to be cached
322 }
323
324 wfProfileOut( $fname );
325 }
326
327 /**
328 * Combine the language default options with any site-specific options
329 * and add the default language variants.
330 *
331 * @return array
332 * @static
333 * @access private
334 */
335 function getDefaultOptions() {
336 /**
337 * Site defaults will override the global/language defaults
338 */
339 global $wgContLang, $wgDefaultUserOptions;
340 $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptions();
341
342 /**
343 * default language setting
344 */
345 $variant = $wgContLang->getPreferredVariant();
346 $defOpt['variant'] = $variant;
347 $defOpt['language'] = $variant;
348
349 return $defOpt;
350 }
351
352 /**
353 * Get a given default option value.
354 *
355 * @param string $opt
356 * @return string
357 * @static
358 * @access public
359 */
360 function getDefaultOption( $opt ) {
361 $defOpts = User::getDefaultOptions();
362 if( isset( $defOpts[$opt] ) ) {
363 return $defOpts[$opt];
364 } else {
365 return '';
366 }
367 }
368
369 /**
370 * Get blocking information
371 * @access private
372 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
373 * non-critical checks are done against slaves. Check when actually saving should be done against
374 * master.
375 */
376 function getBlockedStatus( $bFromSlave = true ) {
377 global $wgEnableSorbs, $wgProxyWhitelist;
378
379 if ( -1 != $this->mBlockedby ) {
380 wfDebug( "User::getBlockedStatus: already loaded.\n" );
381 return;
382 }
383
384 $fname = 'User::getBlockedStatus';
385 wfProfileIn( $fname );
386 wfDebug( "$fname: checking...\n" );
387
388 $this->mBlockedby = 0;
389 $ip = wfGetIP();
390
391 # User/IP blocking
392 $block = new Block();
393 $block->fromMaster( !$bFromSlave );
394 if ( $block->load( $ip , $this->mId ) ) {
395 wfDebug( "$fname: Found block.\n" );
396 $this->mBlockedby = $block->mBy;
397 $this->mBlockreason = $block->mReason;
398 if ( $this->isLoggedIn() ) {
399 $this->spreadBlock();
400 }
401 } else {
402 wfDebug( "$fname: No block.\n" );
403 }
404
405 # Proxy blocking
406 if ( !$this->isSysop() && !in_array( $ip, $wgProxyWhitelist ) ) {
407
408 # Local list
409 if ( wfIsLocallyBlockedProxy( $ip ) ) {
410 $this->mBlockedby = wfMsg( 'proxyblocker' );
411 $this->mBlockreason = wfMsg( 'proxyblockreason' );
412 }
413
414 # DNSBL
415 if ( !$this->mBlockedby && $wgEnableSorbs && !$this->getID() ) {
416 if ( $this->inSorbsBlacklist( $ip ) ) {
417 $this->mBlockedby = wfMsg( 'sorbs' );
418 $this->mBlockreason = wfMsg( 'sorbsreason' );
419 }
420 }
421 }
422
423 # Extensions
424 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
425
426 wfProfileOut( $fname );
427 }
428
429 function inSorbsBlacklist( $ip ) {
430 global $wgEnableSorbs;
431 return $wgEnableSorbs &&
432 $this->inDnsBlacklist( $ip, 'http.dnsbl.sorbs.net.' );
433 }
434
435 function inOpmBlacklist( $ip ) {
436 global $wgEnableOpm;
437 return $wgEnableOpm &&
438 $this->inDnsBlacklist( $ip, 'opm.blitzed.org.' );
439 }
440
441 function inDnsBlacklist( $ip, $base ) {
442 $fname = 'User::inDnsBlacklist';
443 wfProfileIn( $fname );
444
445 $found = false;
446 $host = '';
447
448 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
449 # Make hostname
450 for ( $i=4; $i>=1; $i-- ) {
451 $host .= $m[$i] . '.';
452 }
453 $host .= $base;
454
455 # Send query
456 $ipList = gethostbynamel( $host );
457
458 if ( $ipList ) {
459 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
460 $found = true;
461 } else {
462 wfDebug( "Requested $host, not found in $base.\n" );
463 }
464 }
465
466 wfProfileOut( $fname );
467 return $found;
468 }
469
470 /**
471 * Primitive rate limits: enforce maximum actions per time period
472 * to put a brake on flooding.
473 *
474 * Note: when using a shared cache like memcached, IP-address
475 * last-hit counters will be shared across wikis.
476 *
477 * @return bool true if a rate limiter was tripped
478 * @access public
479 */
480 function pingLimiter( $action='edit' ) {
481 global $wgRateLimits;
482 if( !isset( $wgRateLimits[$action] ) ) {
483 return false;
484 }
485 if( $this->isAllowed( 'delete' ) ) {
486 // goddam cabal
487 return false;
488 }
489
490 global $wgMemc, $wgDBname, $wgRateLimitLog;
491 $fname = 'User::pingLimiter';
492 wfProfileIn( $fname );
493
494 $limits = $wgRateLimits[$action];
495 $keys = array();
496 $id = $this->getId();
497 $ip = wfGetIP();
498
499 if( isset( $limits['anon'] ) && $id == 0 ) {
500 $keys["$wgDBname:limiter:$action:anon"] = $limits['anon'];
501 }
502
503 if( isset( $limits['user'] ) && $id != 0 ) {
504 $keys["$wgDBname:limiter:$action:user:$id"] = $limits['user'];
505 }
506 if( $this->isNewbie() ) {
507 if( isset( $limits['newbie'] ) && $id != 0 ) {
508 $keys["$wgDBname:limiter:$action:user:$id"] = $limits['newbie'];
509 }
510 if( isset( $limits['ip'] ) ) {
511 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
512 }
513 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
514 $subnet = $matches[1];
515 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
516 }
517 }
518
519 $triggered = false;
520 foreach( $keys as $key => $limit ) {
521 list( $max, $period ) = $limit;
522 $summary = "(limit $max in {$period}s)";
523 $count = $wgMemc->get( $key );
524 if( $count ) {
525 if( $count > $max ) {
526 wfDebug( "$fname: tripped! $key at $count $summary\n" );
527 if( $wgRateLimitLog ) {
528 @error_log( wfTimestamp( TS_MW ) . ' ' . $wgDBname . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
529 }
530 $triggered = true;
531 } else {
532 wfDebug( "$fname: ok. $key at $count $summary\n" );
533 }
534 } else {
535 wfDebug( "$fname: adding record for $key $summary\n" );
536 $wgMemc->add( $key, 1, intval( $period ) );
537 }
538 $wgMemc->incr( $key );
539 }
540
541 wfProfileOut( $fname );
542 return $triggered;
543 }
544
545 /**
546 * Check if user is blocked
547 * @return bool True if blocked, false otherwise
548 */
549 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
550 wfDebug( "User::isBlocked: enter\n" );
551 $this->getBlockedStatus( $bFromSlave );
552 return $this->mBlockedby !== 0;
553 }
554
555 /**
556 * Check if user is blocked from editing a particular article
557 */
558 function isBlockedFrom( $title, $bFromSlave = false ) {
559 global $wgBlockAllowsUTEdit;
560 $fname = 'User::isBlockedFrom';
561 wfProfileIn( $fname );
562 wfDebug( "$fname: enter\n" );
563
564 if ( $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
565 $title->getNamespace() == NS_USER_TALK )
566 {
567 $blocked = false;
568 wfDebug( "$fname: self-talk page, ignoring any blocks\n" );
569 } else {
570 wfDebug( "$fname: asking isBlocked()\n" );
571 $blocked = $this->isBlocked( $bFromSlave );
572 }
573 wfProfileOut( $fname );
574 return $blocked;
575 }
576
577 /**
578 * Get name of blocker
579 * @return string name of blocker
580 */
581 function blockedBy() {
582 $this->getBlockedStatus();
583 return $this->mBlockedby;
584 }
585
586 /**
587 * Get blocking reason
588 * @return string Blocking reason
589 */
590 function blockedFor() {
591 $this->getBlockedStatus();
592 return $this->mBlockreason;
593 }
594
595 /**
596 * Initialise php session
597 */
598 function SetupSession() {
599 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
600 if( $wgSessionsInMemcached ) {
601 require_once( 'MemcachedSessions.php' );
602 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
603 # If it's left on 'user' or another setting from another
604 # application, it will end up failing. Try to recover.
605 ini_set ( 'session.save_handler', 'files' );
606 }
607 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
608 session_cache_limiter( 'private, must-revalidate' );
609 @session_start();
610 }
611
612 /**
613 * Create a new user object using data from session
614 * @static
615 */
616 function loadFromSession() {
617 global $wgMemc, $wgDBname;
618
619 if ( isset( $_SESSION['wsUserID'] ) ) {
620 if ( 0 != $_SESSION['wsUserID'] ) {
621 $sId = $_SESSION['wsUserID'];
622 } else {
623 return new User();
624 }
625 } else if ( isset( $_COOKIE["{$wgDBname}UserID"] ) ) {
626 $sId = intval( $_COOKIE["{$wgDBname}UserID"] );
627 $_SESSION['wsUserID'] = $sId;
628 } else {
629 return new User();
630 }
631 if ( isset( $_SESSION['wsUserName'] ) ) {
632 $sName = $_SESSION['wsUserName'];
633 } else if ( isset( $_COOKIE["{$wgDBname}UserName"] ) ) {
634 $sName = $_COOKIE["{$wgDBname}UserName"];
635 $_SESSION['wsUserName'] = $sName;
636 } else {
637 return new User();
638 }
639
640 $passwordCorrect = FALSE;
641 $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
642 if( !is_object( $user ) || $user->mVersion < MW_USER_VERSION ) {
643 # Expire old serialized objects; they may be corrupt.
644 $user = false;
645 }
646 if($makenew = !$user) {
647 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
648 $user = new User();
649 $user->mId = $sId;
650 $user->loadFromDatabase();
651 } else {
652 wfDebug( "User::loadFromSession() got from cache!\n" );
653 }
654
655 if ( isset( $_SESSION['wsToken'] ) ) {
656 $passwordCorrect = $_SESSION['wsToken'] == $user->mToken;
657 } else if ( isset( $_COOKIE["{$wgDBname}Token"] ) ) {
658 $passwordCorrect = $user->mToken == $_COOKIE["{$wgDBname}Token"];
659 } else {
660 return new User(); # Can't log in from session
661 }
662
663 if ( ( $sName == $user->mName ) && $passwordCorrect ) {
664 if($makenew) {
665 if($wgMemc->set( $key, $user ))
666 wfDebug( "User::loadFromSession() successfully saved user\n" );
667 else
668 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
669 }
670 return $user;
671 }
672 return new User(); # Can't log in from session
673 }
674
675 /**
676 * Load a user from the database
677 */
678 function loadFromDatabase() {
679 $fname = "User::loadFromDatabase";
680
681 # Counter-intuitive, breaks various things, use User::setLoaded() if you want to suppress
682 # loading in a command line script, don't assume all command line scripts need it like this
683 #if ( $this->mDataLoaded || $wgCommandLineMode ) {
684 if ( $this->mDataLoaded ) {
685 return;
686 }
687
688 # Paranoia
689 $this->mId = intval( $this->mId );
690
691 /** Anonymous user */
692 if( !$this->mId ) {
693 /** Get rights */
694 $this->mRights = $this->getGroupPermissions( array( '*' ) );
695 $this->mDataLoaded = true;
696 return;
697 } # the following stuff is for non-anonymous users only
698
699 $dbr =& wfGetDB( DB_SLAVE );
700 $s = $dbr->selectRow( 'user', array( 'user_name','user_password','user_newpassword','user_email',
701 'user_email_authenticated',
702 'user_real_name','user_options','user_touched', 'user_token' ),
703 array( 'user_id' => $this->mId ), $fname );
704
705 if ( $s !== false ) {
706 $this->mName = $s->user_name;
707 $this->mEmail = $s->user_email;
708 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $s->user_email_authenticated );
709 $this->mRealName = $s->user_real_name;
710 $this->mPassword = $s->user_password;
711 $this->mNewpassword = $s->user_newpassword;
712 $this->decodeOptions( $s->user_options );
713 $this->mTouched = wfTimestamp(TS_MW,$s->user_touched);
714 $this->mToken = $s->user_token;
715
716 $res = $dbr->select( 'user_groups',
717 array( 'ug_group' ),
718 array( 'ug_user' => $this->mId ),
719 $fname );
720 $this->mGroups = array();
721 while( $row = $dbr->fetchObject( $res ) ) {
722 $this->mGroups[] = $row->ug_group;
723 }
724 $effectiveGroups = array_merge( array( '*', 'user' ), $this->mGroups );
725 $this->mRights = $this->getGroupPermissions( $effectiveGroups );
726 }
727
728 $this->mDataLoaded = true;
729 }
730
731 function getID() { return $this->mId; }
732 function setID( $v ) {
733 $this->mId = $v;
734 $this->mDataLoaded = false;
735 }
736
737 function getName() {
738 $this->loadFromDatabase();
739 if ( $this->mName === false ) {
740 $this->mName = wfGetIP();
741 }
742 return $this->mName;
743 }
744
745 function setName( $str ) {
746 $this->loadFromDatabase();
747 $this->mName = $str;
748 }
749
750
751 /**
752 * Return the title dbkey form of the name, for eg user pages.
753 * @return string
754 * @access public
755 */
756 function getTitleKey() {
757 return str_replace( ' ', '_', $this->getName() );
758 }
759
760 function getNewtalk() {
761 $this->loadFromDatabase();
762
763 # Load the newtalk status if it is unloaded (mNewtalk=-1)
764 if( $this->mNewtalk === -1 ) {
765 $this->mNewtalk = false; # reset talk page status
766
767 # Check memcached separately for anons, who have no
768 # entire User object stored in there.
769 if( !$this->mId ) {
770 global $wgDBname, $wgMemc;
771 $key = "$wgDBname:newtalk:ip:" . $this->getName();
772 $newtalk = $wgMemc->get( $key );
773 if( is_integer( $newtalk ) ) {
774 $this->mNewtalk = (bool)$newtalk;
775 } else {
776 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName() );
777 $wgMemc->set( $key, $this->mNewtalk, time() ); // + 1800 );
778 }
779 } else {
780 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
781 }
782 }
783
784 return (bool)$this->mNewtalk;
785 }
786
787 /**
788 * Perform a user_newtalk check on current slaves; if the memcached data
789 * is funky we don't want newtalk state to get stuck on save, as that's
790 * damn annoying.
791 *
792 * @param string $field
793 * @param mixed $id
794 * @return bool
795 * @access private
796 */
797 function checkNewtalk( $field, $id ) {
798 $fname = 'User::checkNewtalk';
799 $dbr =& wfGetDB( DB_SLAVE );
800 $ok = $dbr->selectField( 'user_newtalk', $field,
801 array( $field => $id ), $fname );
802 return $ok !== false;
803 }
804
805 /**
806 * Add or update the
807 * @param string $field
808 * @param mixed $id
809 * @access private
810 */
811 function updateNewtalk( $field, $id ) {
812 $fname = 'User::updateNewtalk';
813 if( $this->checkNewtalk( $field, $id ) ) {
814 wfDebug( "$fname already set ($field, $id), ignoring\n" );
815 return false;
816 }
817 $dbw =& wfGetDB( DB_MASTER );
818 $dbw->insert( 'user_newtalk',
819 array( $field => $id ),
820 $fname,
821 'IGNORE' );
822 wfDebug( "$fname: set on ($field, $id)\n" );
823 return true;
824 }
825
826 /**
827 * @param string $field
828 * @param mixed $id
829 * @access private
830 */
831 function deleteNewtalk( $field, $id ) {
832 $fname = 'User::deleteNewtalk';
833 if( !$this->checkNewtalk( $field, $id ) ) {
834 wfDebug( "$fname: already gone ($field, $id), ignoring\n" );
835 return false;
836 }
837 $dbw =& wfGetDB( DB_MASTER );
838 $dbw->delete( 'user_newtalk',
839 array( $field => $id ),
840 $fname );
841 wfDebug( "$fname: killed on ($field, $id)\n" );
842 return true;
843 }
844
845 /**
846 * Update the 'You have new messages!' status.
847 * @param bool $val
848 */
849 function setNewtalk( $val ) {
850 if( wfReadOnly() ) {
851 return;
852 }
853
854 $this->loadFromDatabase();
855 $this->mNewtalk = $val;
856
857 $fname = 'User::setNewtalk';
858
859 if( $this->isAnon() ) {
860 $field = 'user_ip';
861 $id = $this->getName();
862 } else {
863 $field = 'user_id';
864 $id = $this->getId();
865 }
866
867 if( $val ) {
868 $changed = $this->updateNewtalk( $field, $id );
869 } else {
870 $changed = $this->deleteNewtalk( $field, $id );
871 }
872
873 if( $changed ) {
874 if( $this->isAnon() ) {
875 // Anons have a separate memcached space, since
876 // user records aren't kept for them.
877 global $wgDBname, $wgMemc;
878 $key = "$wgDBname:newtalk:ip:$value";
879 $wgMemc->set( $key, $val ? 1 : 0 );
880 } else {
881 if( $val ) {
882 // Make sure the user page is watched, so a notification
883 // will be sent out if enabled.
884 $this->addWatch( $this->getTalkPage() );
885 }
886 }
887 $this->invalidateCache();
888 $this->saveSettings();
889 }
890 }
891
892 function invalidateCache() {
893 global $wgClockSkewFudge;
894 $this->loadFromDatabase();
895 $this->mTouched = wfTimestamp(TS_MW, time() + $wgClockSkewFudge );
896 # Don't forget to save the options after this or
897 # it won't take effect!
898 }
899
900 function validateCache( $timestamp ) {
901 $this->loadFromDatabase();
902 return ($timestamp >= $this->mTouched);
903 }
904
905 /**
906 * Encrypt a password.
907 * It can eventuall salt a password @see User::addSalt()
908 * @param string $p clear Password.
909 * @return string Encrypted password.
910 */
911 function encryptPassword( $p ) {
912 return wfEncryptPassword( $this->mId, $p );
913 }
914
915 # Set the password and reset the random token
916 function setPassword( $str ) {
917 $this->loadFromDatabase();
918 $this->setToken();
919 $this->mPassword = $this->encryptPassword( $str );
920 $this->mNewpassword = '';
921 }
922
923 # Set the random token (used for persistent authentication)
924 function setToken( $token = false ) {
925 global $wgSecretKey, $wgProxyKey, $wgDBname;
926 if ( !$token ) {
927 if ( $wgSecretKey ) {
928 $key = $wgSecretKey;
929 } elseif ( $wgProxyKey ) {
930 $key = $wgProxyKey;
931 } else {
932 $key = microtime();
933 }
934 $this->mToken = md5( $key . mt_rand( 0, 0x7fffffff ) . $wgDBname . $this->mId );
935 } else {
936 $this->mToken = $token;
937 }
938 }
939
940
941 function setCookiePassword( $str ) {
942 $this->loadFromDatabase();
943 $this->mCookiePassword = md5( $str );
944 }
945
946 function setNewpassword( $str ) {
947 $this->loadFromDatabase();
948 $this->mNewpassword = $this->encryptPassword( $str );
949 }
950
951 function getEmail() {
952 $this->loadFromDatabase();
953 return $this->mEmail;
954 }
955
956 function getEmailAuthenticationTimestamp() {
957 $this->loadFromDatabase();
958 return $this->mEmailAuthenticated;
959 }
960
961 function setEmail( $str ) {
962 $this->loadFromDatabase();
963 $this->mEmail = $str;
964 }
965
966 function getRealName() {
967 $this->loadFromDatabase();
968 return $this->mRealName;
969 }
970
971 function setRealName( $str ) {
972 $this->loadFromDatabase();
973 $this->mRealName = $str;
974 }
975
976 function getOption( $oname ) {
977 $this->loadFromDatabase();
978 if ( array_key_exists( $oname, $this->mOptions ) ) {
979 return trim( $this->mOptions[$oname] );
980 } else {
981 return '';
982 }
983 }
984
985 function setOption( $oname, $val ) {
986 $this->loadFromDatabase();
987 if ( $oname == 'skin' ) {
988 # Clear cached skin, so the new one displays immediately in Special:Preferences
989 unset( $this->mSkin );
990 }
991 $this->mOptions[$oname] = $val;
992 $this->invalidateCache();
993 }
994
995 function getRights() {
996 $this->loadFromDatabase();
997 return $this->mRights;
998 }
999
1000 /**
1001 * Get the list of explicit group memberships this user has.
1002 * The implicit * and user groups are not included.
1003 * @return array of strings
1004 */
1005 function getGroups() {
1006 $this->loadFromDatabase();
1007 return $this->mGroups;
1008 }
1009
1010 /**
1011 * Get the list of implicit group memberships this user has.
1012 * This includes all explicit groups, plus 'user' if logged in
1013 * and '*' for all accounts.
1014 * @return array of strings
1015 */
1016 function getEffectiveGroups() {
1017 $base = array( '*' );
1018 if( $this->isLoggedIn() ) {
1019 $base[] = 'user';
1020 }
1021 return array_merge( $base, $this->getGroups() );
1022 }
1023
1024 /**
1025 * Remove the user from the given group.
1026 * This takes immediate effect.
1027 * @string $group
1028 */
1029 function addGroup( $group ) {
1030 $dbw =& wfGetDB( DB_MASTER );
1031 $dbw->insert( 'user_groups',
1032 array(
1033 'ug_user' => $this->getID(),
1034 'ug_group' => $group,
1035 ),
1036 'User::addGroup',
1037 array( 'IGNORE' ) );
1038
1039 $this->mGroups = array_merge( $this->mGroups, array( $group ) );
1040 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups() );
1041
1042 $this->invalidateCache();
1043 $this->saveSettings();
1044 }
1045
1046 /**
1047 * Remove the user from the given group.
1048 * This takes immediate effect.
1049 * @string $group
1050 */
1051 function removeGroup( $group ) {
1052 $dbw =& wfGetDB( DB_MASTER );
1053 $dbw->delete( 'user_groups',
1054 array(
1055 'ug_user' => $this->getID(),
1056 'ug_group' => $group,
1057 ),
1058 'User::removeGroup' );
1059
1060 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
1061 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups() );
1062
1063 $this->invalidateCache();
1064 $this->saveSettings();
1065 }
1066
1067
1068 /**
1069 * A more legible check for non-anonymousness.
1070 * Returns true if the user is not an anonymous visitor.
1071 *
1072 * @return bool
1073 */
1074 function isLoggedIn() {
1075 return( $this->getID() != 0 );
1076 }
1077
1078 /**
1079 * A more legible check for anonymousness.
1080 * Returns true if the user is an anonymous visitor.
1081 *
1082 * @return bool
1083 */
1084 function isAnon() {
1085 return !$this->isLoggedIn();
1086 }
1087
1088 /**
1089 * Check if a user is sysop
1090 * @deprecated
1091 */
1092 function isSysop() {
1093 return $this->isAllowed( 'protect' );
1094 }
1095
1096 /** @deprecated */
1097 function isDeveloper() {
1098 return $this->isAllowed( 'siteadmin' );
1099 }
1100
1101 /** @deprecated */
1102 function isBureaucrat() {
1103 return $this->isAllowed( 'makesysop' );
1104 }
1105
1106 /**
1107 * Whether the user is a bot
1108 * @todo need to be migrated to the new user level management sytem
1109 */
1110 function isBot() {
1111 $this->loadFromDatabase();
1112 return in_array( 'bot', $this->mRights );
1113 }
1114
1115 /**
1116 * Check if user is allowed to access a feature / make an action
1117 * @param string $action Action to be checked (see $wgAvailableRights in Defines.php for possible actions).
1118 * @return boolean True: action is allowed, False: action should not be allowed
1119 */
1120 function isAllowed($action='') {
1121 $this->loadFromDatabase();
1122 return in_array( $action , $this->mRights );
1123 }
1124
1125 /**
1126 * Load a skin if it doesn't exist or return it
1127 * @todo FIXME : need to check the old failback system [AV]
1128 */
1129 function &getSkin() {
1130 global $IP, $wgRequest;
1131 if ( ! isset( $this->mSkin ) ) {
1132 $fname = 'User::getSkin';
1133 wfProfileIn( $fname );
1134
1135 # get all skin names available
1136 $skinNames = Skin::getSkinNames();
1137
1138 # get the user skin
1139 $userSkin = $this->getOption( 'skin' );
1140 $userSkin = $wgRequest->getVal('useskin', $userSkin);
1141
1142 $this->mSkin =& Skin::newFromKey( $userSkin );
1143 wfProfileOut( $fname );
1144 }
1145 return $this->mSkin;
1146 }
1147
1148 /**#@+
1149 * @param string $title Article title to look at
1150 */
1151
1152 /**
1153 * Check watched status of an article
1154 * @return bool True if article is watched
1155 */
1156 function isWatched( $title ) {
1157 $wl = WatchedItem::fromUserTitle( $this, $title );
1158 return $wl->isWatched();
1159 }
1160
1161 /**
1162 * Watch an article
1163 */
1164 function addWatch( $title ) {
1165 $wl = WatchedItem::fromUserTitle( $this, $title );
1166 $wl->addWatch();
1167 $this->invalidateCache();
1168 }
1169
1170 /**
1171 * Stop watching an article
1172 */
1173 function removeWatch( $title ) {
1174 $wl = WatchedItem::fromUserTitle( $this, $title );
1175 $wl->removeWatch();
1176 $this->invalidateCache();
1177 }
1178
1179 /**
1180 * Clear the user's notification timestamp for the given title.
1181 * If e-notif e-mails are on, they will receive notification mails on
1182 * the next change of the page if it's watched etc.
1183 */
1184 function clearNotification( &$title ) {
1185 global $wgUser, $wgUseEnotif;
1186
1187 if ($title->getNamespace() == NS_USER_TALK &&
1188 $title->getText() == $this->getName() ) {
1189 $this->setNewtalk( false );
1190 }
1191
1192 if( !$wgUseEnotif ) {
1193 return;
1194 }
1195
1196 if( $this->isAnon() ) {
1197 // Nothing else to do...
1198 return;
1199 }
1200
1201 // Only update the timestamp if the page is being watched.
1202 // The query to find out if it is watched is cached both in memcached and per-invocation,
1203 // and when it does have to be executed, it can be on a slave
1204 // If this is the user's newtalk page, we always update the timestamp
1205 if ($title->getNamespace() == NS_USER_TALK &&
1206 $title->getText() == $wgUser->getName())
1207 {
1208 $watched = true;
1209 } elseif ( $this->getID() == $wgUser->getID() ) {
1210 $watched = $title->userIsWatching();
1211 } else {
1212 $watched = true;
1213 }
1214
1215 // If the page is watched by the user (or may be watched), update the timestamp on any
1216 // any matching rows
1217 if ( $watched ) {
1218 $dbw =& wfGetDB( DB_MASTER );
1219 $success = $dbw->update( 'watchlist',
1220 array( /* SET */
1221 'wl_notificationtimestamp' => NULL
1222 ), array( /* WHERE */
1223 'wl_title' => $title->getDBkey(),
1224 'wl_namespace' => $title->getNamespace(),
1225 'wl_user' => $this->getID()
1226 ), 'User::clearLastVisited'
1227 );
1228 }
1229 }
1230
1231 /**#@-*/
1232
1233 /**
1234 * Resets all of the given user's page-change notification timestamps.
1235 * If e-notif e-mails are on, they will receive notification mails on
1236 * the next change of any watched page.
1237 *
1238 * @param int $currentUser user ID number
1239 * @access public
1240 */
1241 function clearAllNotifications( $currentUser ) {
1242 global $wgUseEnotif;
1243 if ( !$wgUseEnotif ) {
1244 $this->setNewtalk( false );
1245 return;
1246 }
1247 if( $currentUser != 0 ) {
1248
1249 $dbw =& wfGetDB( DB_MASTER );
1250 $success = $dbw->update( 'watchlist',
1251 array( /* SET */
1252 'wl_notificationtimestamp' => 0
1253 ), array( /* WHERE */
1254 'wl_user' => $currentUser
1255 ), 'UserMailer::clearAll'
1256 );
1257
1258 # we also need to clear here the "you have new message" notification for the own user_talk page
1259 # This is cleared one page view later in Article::viewUpdates();
1260 }
1261 }
1262
1263 /**
1264 * @access private
1265 * @return string Encoding options
1266 */
1267 function encodeOptions() {
1268 $a = array();
1269 foreach ( $this->mOptions as $oname => $oval ) {
1270 array_push( $a, $oname.'='.$oval );
1271 }
1272 $s = implode( "\n", $a );
1273 return $s;
1274 }
1275
1276 /**
1277 * @access private
1278 */
1279 function decodeOptions( $str ) {
1280 $a = explode( "\n", $str );
1281 foreach ( $a as $s ) {
1282 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1283 $this->mOptions[$m[1]] = $m[2];
1284 }
1285 }
1286 }
1287
1288 function setCookies() {
1289 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
1290 if ( 0 == $this->mId ) return;
1291 $this->loadFromDatabase();
1292 $exp = time() + $wgCookieExpiration;
1293
1294 $_SESSION['wsUserID'] = $this->mId;
1295 setcookie( $wgDBname.'UserID', $this->mId, $exp, $wgCookiePath, $wgCookieDomain );
1296
1297 $_SESSION['wsUserName'] = $this->getName();
1298 setcookie( $wgDBname.'UserName', $this->getName(), $exp, $wgCookiePath, $wgCookieDomain );
1299
1300 $_SESSION['wsToken'] = $this->mToken;
1301 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1302 setcookie( $wgDBname.'Token', $this->mToken, $exp, $wgCookiePath, $wgCookieDomain );
1303 } else {
1304 setcookie( $wgDBname.'Token', '', time() - 3600 );
1305 }
1306 }
1307
1308 /**
1309 * Logout user
1310 * It will clean the session cookie
1311 */
1312 function logout() {
1313 global $wgCookiePath, $wgCookieDomain, $wgDBname;
1314 $this->loadDefaults();
1315 $this->setLoaded( true );
1316
1317 $_SESSION['wsUserID'] = 0;
1318
1319 setcookie( $wgDBname.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
1320 setcookie( $wgDBname.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
1321
1322 # Remember when user logged out, to prevent seeing cached pages
1323 setcookie( $wgDBname.'LoggedOut', wfTimestampNow(), time() + 86400, $wgCookiePath, $wgCookieDomain );
1324 }
1325
1326 /**
1327 * Save object settings into database
1328 */
1329 function saveSettings() {
1330 global $wgMemc, $wgDBname, $wgUseEnotif;
1331 $fname = 'User::saveSettings';
1332
1333 if ( wfReadOnly() ) { return; }
1334 if ( 0 == $this->mId ) { return; }
1335
1336 $dbw =& wfGetDB( DB_MASTER );
1337 $dbw->update( 'user',
1338 array( /* SET */
1339 'user_name' => $this->mName,
1340 'user_password' => $this->mPassword,
1341 'user_newpassword' => $this->mNewpassword,
1342 'user_real_name' => $this->mRealName,
1343 'user_email' => $this->mEmail,
1344 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
1345 'user_options' => $this->encodeOptions(),
1346 'user_touched' => $dbw->timestamp($this->mTouched),
1347 'user_token' => $this->mToken
1348 ), array( /* WHERE */
1349 'user_id' => $this->mId
1350 ), $fname
1351 );
1352 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
1353 }
1354
1355
1356 /**
1357 * Checks if a user with the given name exists, returns the ID
1358 */
1359 function idForName() {
1360 $fname = 'User::idForName';
1361
1362 $gotid = 0;
1363 $s = trim( $this->getName() );
1364 if ( 0 == strcmp( '', $s ) ) return 0;
1365
1366 $dbr =& wfGetDB( DB_SLAVE );
1367 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), $fname );
1368 if ( $id === false ) {
1369 $id = 0;
1370 }
1371 return $id;
1372 }
1373
1374 /**
1375 * Add user object to the database
1376 */
1377 function addToDatabase() {
1378 $fname = 'User::addToDatabase';
1379 $dbw =& wfGetDB( DB_MASTER );
1380 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1381 $dbw->insert( 'user',
1382 array(
1383 'user_id' => $seqVal,
1384 'user_name' => $this->mName,
1385 'user_password' => $this->mPassword,
1386 'user_newpassword' => $this->mNewpassword,
1387 'user_email' => $this->mEmail,
1388 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
1389 'user_real_name' => $this->mRealName,
1390 'user_options' => $this->encodeOptions(),
1391 'user_token' => $this->mToken
1392 ), $fname
1393 );
1394 $this->mId = $dbw->insertId();
1395 }
1396
1397 function spreadBlock() {
1398 # If the (non-anonymous) user is blocked, this function will block any IP address
1399 # that they successfully log on from.
1400 $fname = 'User::spreadBlock';
1401
1402 wfDebug( "User:spreadBlock()\n" );
1403 if ( $this->mId == 0 ) {
1404 return;
1405 }
1406
1407 $userblock = Block::newFromDB( '', $this->mId );
1408 if ( !$userblock->isValid() ) {
1409 return;
1410 }
1411
1412 # Check if this IP address is already blocked
1413 $ipblock = Block::newFromDB( wfGetIP() );
1414 if ( $ipblock->isValid() ) {
1415 # If the user is already blocked. Then check if the autoblock would
1416 # excede the user block. If it would excede, then do nothing, else
1417 # prolong block time
1418 if ($userblock->mExpiry &&
1419 ($userblock->mExpiry < Block::getAutoblockExpiry($ipblock->mTimestamp))) {
1420 return;
1421 }
1422 # Just update the timestamp
1423 $ipblock->updateTimestamp();
1424 return;
1425 }
1426
1427 # Make a new block object with the desired properties
1428 wfDebug( "Autoblocking {$this->mName}@" . wfGetIP() . "\n" );
1429 $ipblock->mAddress = wfGetIP();
1430 $ipblock->mUser = 0;
1431 $ipblock->mBy = $userblock->mBy;
1432 $ipblock->mReason = wfMsg( 'autoblocker', $this->getName(), $userblock->mReason );
1433 $ipblock->mTimestamp = wfTimestampNow();
1434 $ipblock->mAuto = 1;
1435 # If the user is already blocked with an expiry date, we don't
1436 # want to pile on top of that!
1437 if($userblock->mExpiry) {
1438 $ipblock->mExpiry = min ( $userblock->mExpiry, Block::getAutoblockExpiry( $ipblock->mTimestamp ));
1439 } else {
1440 $ipblock->mExpiry = Block::getAutoblockExpiry( $ipblock->mTimestamp );
1441 }
1442
1443 # Insert it
1444 $ipblock->insert();
1445
1446 }
1447
1448 function getPageRenderingHash() {
1449 global $wgContLang;
1450 if( $this->mHash ){
1451 return $this->mHash;
1452 }
1453
1454 // stubthreshold is only included below for completeness,
1455 // it will always be 0 when this function is called by parsercache.
1456
1457 $confstr = $this->getOption( 'math' );
1458 $confstr .= '!' . $this->getOption( 'stubthreshold' );
1459 $confstr .= '!' . $this->getOption( 'date' );
1460 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ? '1' : '');
1461 $confstr .= '!' . $this->getOption( 'language' );
1462 $confstr .= '!' . $this->getOption( 'thumbsize' );
1463 // add in language specific options, if any
1464 $extra = $wgContLang->getExtraHashOptions();
1465 $confstr .= $extra;
1466
1467 $this->mHash = $confstr;
1468 return $confstr ;
1469 }
1470
1471 function isAllowedToCreateAccount() {
1472 return $this->isAllowed( 'createaccount' ) && !$this->isBlocked();
1473 }
1474
1475 /**
1476 * Set mDataLoaded, return previous value
1477 * Use this to prevent DB access in command-line scripts or similar situations
1478 */
1479 function setLoaded( $loaded ) {
1480 return wfSetVar( $this->mDataLoaded, $loaded );
1481 }
1482
1483 /**
1484 * Get this user's personal page title.
1485 *
1486 * @return Title
1487 * @access public
1488 */
1489 function getUserPage() {
1490 return Title::makeTitle( NS_USER, $this->getName() );
1491 }
1492
1493 /**
1494 * Get this user's talk page title.
1495 *
1496 * @return Title
1497 * @access public
1498 */
1499 function getTalkPage() {
1500 $title = $this->getUserPage();
1501 return $title->getTalkPage();
1502 }
1503
1504 /**
1505 * @static
1506 */
1507 function getMaxID() {
1508 static $res; // cache
1509
1510 if ( isset( $res ) )
1511 return $res;
1512 else {
1513 $dbr =& wfGetDB( DB_SLAVE );
1514 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
1515 }
1516 }
1517
1518 /**
1519 * Determine whether the user is a newbie. Newbies are either
1520 * anonymous IPs, or the 1% most recently created accounts.
1521 * Bots and sysops are excluded.
1522 * @return bool True if it is a newbie.
1523 */
1524 function isNewbie() {
1525 return $this->isAnon() || $this->mId > User::getMaxID() * 0.99 && !$this->isAllowed( 'delete' ) && !$this->isBot();
1526 }
1527
1528 /**
1529 * Check to see if the given clear-text password is one of the accepted passwords
1530 * @param string $password User password.
1531 * @return bool True if the given password is correct otherwise False.
1532 */
1533 function checkPassword( $password ) {
1534 global $wgAuth, $wgMinimalPasswordLength;
1535 $this->loadFromDatabase();
1536
1537 // Even though we stop people from creating passwords that
1538 // are shorter than this, doesn't mean people wont be able
1539 // to. Certain authentication plugins do NOT want to save
1540 // domain passwords in a mysql database, so we should
1541 // check this (incase $wgAuth->strict() is false).
1542 if( strlen( $password ) < $wgMinimalPasswordLength ) {
1543 return false;
1544 }
1545
1546 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
1547 return true;
1548 } elseif( $wgAuth->strict() ) {
1549 /* Auth plugin doesn't allow local authentication */
1550 return false;
1551 }
1552 $ep = $this->encryptPassword( $password );
1553 if ( 0 == strcmp( $ep, $this->mPassword ) ) {
1554 return true;
1555 } elseif ( ($this->mNewpassword != '') && (0 == strcmp( $ep, $this->mNewpassword )) ) {
1556 return true;
1557 } elseif ( function_exists( 'iconv' ) ) {
1558 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
1559 # Check for this with iconv
1560 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252', $password ) );
1561 if ( 0 == strcmp( $cp1252hash, $this->mPassword ) ) {
1562 return true;
1563 }
1564 }
1565 return false;
1566 }
1567
1568 /**
1569 * Initialize (if necessary) and return a session token value
1570 * which can be used in edit forms to show that the user's
1571 * login credentials aren't being hijacked with a foreign form
1572 * submission.
1573 *
1574 * @param mixed $salt - Optional function-specific data for hash.
1575 * Use a string or an array of strings.
1576 * @return string
1577 * @access public
1578 */
1579 function editToken( $salt = '' ) {
1580 if( !isset( $_SESSION['wsEditToken'] ) ) {
1581 $token = $this->generateToken();
1582 $_SESSION['wsEditToken'] = $token;
1583 } else {
1584 $token = $_SESSION['wsEditToken'];
1585 }
1586 if( is_array( $salt ) ) {
1587 $salt = implode( '|', $salt );
1588 }
1589 return md5( $token . $salt );
1590 }
1591
1592 /**
1593 * Generate a hex-y looking random token for various uses.
1594 * Could be made more cryptographically sure if someone cares.
1595 * @return string
1596 */
1597 function generateToken( $salt = '' ) {
1598 $token = dechex( mt_rand() ) . dechex( mt_rand() );
1599 return md5( $token . $salt );
1600 }
1601
1602 /**
1603 * Check given value against the token value stored in the session.
1604 * A match should confirm that the form was submitted from the
1605 * user's own login session, not a form submission from a third-party
1606 * site.
1607 *
1608 * @param string $val - the input value to compare
1609 * @param string $salt - Optional function-specific data for hash
1610 * @return bool
1611 * @access public
1612 */
1613 function matchEditToken( $val, $salt = '' ) {
1614 global $wgMemc;
1615
1616 /*
1617 if ( !isset( $_SESSION['wsEditToken'] ) ) {
1618 $logfile = '/home/wikipedia/logs/session_debug/session.log';
1619 $mckey = memsess_key( session_id() );
1620 $uname = @posix_uname();
1621 $msg = "wsEditToken not set!\n" .
1622 'apache server=' . $uname['nodename'] . "\n" .
1623 'session_id = ' . session_id() . "\n" .
1624 '$_SESSION=' . var_export( $_SESSION, true ) . "\n" .
1625 '$_COOKIE=' . var_export( $_COOKIE, true ) . "\n" .
1626 "mc get($mckey) = " . var_export( $wgMemc->get( $mckey ), true ) . "\n\n\n";
1627
1628 @error_log( $msg, 3, $logfile );
1629 }
1630 */
1631 return ( $val == $this->editToken( $salt ) );
1632 }
1633
1634 /**
1635 * Generate a new e-mail confirmation token and send a confirmation
1636 * mail to the user's given address.
1637 *
1638 * @return mixed True on success, a WikiError object on failure.
1639 */
1640 function sendConfirmationMail() {
1641 global $wgContLang;
1642 $url = $this->confirmationTokenUrl( $expiration );
1643 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
1644 wfMsg( 'confirmemail_body',
1645 wfGetIP(),
1646 $this->getName(),
1647 $url,
1648 $wgContLang->timeanddate( $expiration, false ) ) );
1649 }
1650
1651 /**
1652 * Send an e-mail to this user's account. Does not check for
1653 * confirmed status or validity.
1654 *
1655 * @param string $subject
1656 * @param string $body
1657 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
1658 * @return mixed True on success, a WikiError object on failure.
1659 */
1660 function sendMail( $subject, $body, $from = null ) {
1661 if( is_null( $from ) ) {
1662 global $wgPasswordSender;
1663 $from = $wgPasswordSender;
1664 }
1665
1666 require_once( 'UserMailer.php' );
1667 $to = new MailAddress( $this );
1668 $sender = new MailAddress( $from );
1669 $error = userMailer( $to, $sender, $subject, $body );
1670
1671 if( $error == '' ) {
1672 return true;
1673 } else {
1674 return new WikiError( $error );
1675 }
1676 }
1677
1678 /**
1679 * Generate, store, and return a new e-mail confirmation code.
1680 * A hash (unsalted since it's used as a key) is stored.
1681 * @param &$expiration mixed output: accepts the expiration time
1682 * @return string
1683 * @access private
1684 */
1685 function confirmationToken( &$expiration ) {
1686 $fname = 'User::confirmationToken';
1687
1688 $now = time();
1689 $expires = $now + 7 * 24 * 60 * 60;
1690 $expiration = wfTimestamp( TS_MW, $expires );
1691
1692 $token = $this->generateToken( $this->mId . $this->mEmail . $expires );
1693 $hash = md5( $token );
1694
1695 $dbw =& wfGetDB( DB_MASTER );
1696 $dbw->update( 'user',
1697 array( 'user_email_token' => $hash,
1698 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
1699 array( 'user_id' => $this->mId ),
1700 $fname );
1701
1702 return $token;
1703 }
1704
1705 /**
1706 * Generate and store a new e-mail confirmation token, and return
1707 * the URL the user can use to confirm.
1708 * @param &$expiration mixed output: accepts the expiration time
1709 * @return string
1710 * @access private
1711 */
1712 function confirmationTokenUrl( &$expiration ) {
1713 $token = $this->confirmationToken( $expiration );
1714 $title = Title::makeTitle( NS_SPECIAL, 'Confirmemail/' . $token );
1715 return $title->getFullUrl();
1716 }
1717
1718 /**
1719 * Mark the e-mail address confirmed and save.
1720 */
1721 function confirmEmail() {
1722 $this->loadFromDatabase();
1723 $this->mEmailAuthenticated = wfTimestampNow();
1724 $this->saveSettings();
1725 return true;
1726 }
1727
1728 /**
1729 * Is this user allowed to send e-mails within limits of current
1730 * site configuration?
1731 * @return bool
1732 */
1733 function canSendEmail() {
1734 return $this->isEmailConfirmed();
1735 }
1736
1737 /**
1738 * Is this user allowed to receive e-mails within limits of current
1739 * site configuration?
1740 * @return bool
1741 */
1742 function canReceiveEmail() {
1743 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
1744 }
1745
1746 /**
1747 * Is this user's e-mail address valid-looking and confirmed within
1748 * limits of the current site configuration?
1749 *
1750 * If $wgEmailAuthentication is on, this may require the user to have
1751 * confirmed their address by returning a code or using a password
1752 * sent to the address from the wiki.
1753 *
1754 * @return bool
1755 */
1756 function isEmailConfirmed() {
1757 global $wgEmailAuthentication;
1758 $this->loadFromDatabase();
1759 if( $this->isAnon() )
1760 return false;
1761 if( !$this->isValidEmailAddr( $this->mEmail ) )
1762 return false;
1763 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
1764 return false;
1765 return true;
1766 }
1767
1768 /**
1769 * @param array $groups list of groups
1770 * @return array list of permission key names for given groups combined
1771 * @static
1772 */
1773 function getGroupPermissions( $groups ) {
1774 global $wgGroupPermissions;
1775 $rights = array();
1776 foreach( $groups as $group ) {
1777 if( isset( $wgGroupPermissions[$group] ) ) {
1778 $rights = array_merge( $rights,
1779 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
1780 }
1781 }
1782 return $rights;
1783 }
1784
1785 /**
1786 * @param string $group key name
1787 * @return string localized descriptive name, if provided
1788 * @static
1789 */
1790 function getGroupName( $group ) {
1791 $key = "group-$group-name";
1792 $name = wfMsg( $key );
1793 if( $name == '' || $name == "&lt;$key&gt;" ) {
1794 return $group;
1795 } else {
1796 return $name;
1797 }
1798 }
1799
1800 /**
1801 * Return the set of defined explicit groups.
1802 * The * and 'user' groups are not included.
1803 * @return array
1804 * @static
1805 */
1806 function getAllGroups() {
1807 global $wgGroupPermissions;
1808 return array_diff(
1809 array_keys( $wgGroupPermissions ),
1810 array( '*', 'user' ) );
1811 }
1812
1813 }
1814
1815 ?>